package org.example.Controller;

import org.example.Forms.MainForm;
import org.example.Forms.testForm;
import org.example.Tool.Component.MessageCard;
import org.example.Tool.IIdentified;
import org.example.Tool.Idtool;
import org.example.dataHandle.Data;
import org.example.dataHandle.RecordArray;
import org.example.dataHandle.TaskRecord;

import java.util.Date;
import java.util.Random;

public class RunTask implements Runnable, IIdentified {
    private final int id;

    protected String Name;

    public TaskType type = TaskType.none;

    protected boolean isRun = false;

    protected TaskRecord<Number> record;

    public String getName() {
        return Name;
    }

    public boolean getIsRun() {
        return isRun;
    }

    public RunTask(String Name){
        this.Name = Name;
        this.id = Idtool.distributeId();
        //test
        this.record = new RecordArray<>();
    }

    protected void EnterEvent(TaskFormNode node){
        if (!node.getIsRun()) {
            node.setFormRecord(record);
            node.runTask(FormManagerNode.FormRunType.RUN_ON_ANOTHER_THREAD);
        }
    }


    public void formEntrance(MessageCard card, TaskFormNode node){
        card.setName(Name);
        card.setRecord(record);
        TaskFormNode start;
        //node.getFormBuilder().setFactory(testForm::new);
        start = node;

        card.setClickEvent(
                () ->{
                    EnterEvent(start);
                }
        );
    }


    @Override
    public void run() {
        isRun = true;
        final long dbt = 100;
        while (isRun){
            try {
                //test
                long num = record.getLatest() == null ? 0 : record.getLatest().getSecond();
                int random = new Random(new Date().getTime()).nextInt();
                record.add(new Data.Pair<>(
                        (random > 0 ? random : -random) % 100
                        ,(num + dbt)));
                Thread.sleep(dbt);
            }
            catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }

    @Override
    public int getId() {
        return id;
    }

    public enum TaskType{
        DataWatching,Calculating,none
    }

}